﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using ProTrack.Api.Helper;
using ProTrack.Dto;
using ProTrack.Entity;
using ProTrack.IServices.PurchaseOrder;
using ProTrack.Report;
using ProTrack.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ProTrack.Api.Controllers
{
    /// <summary>
    /// 采购订单
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class OrderPoController : ControllerBase
    {
        /// <summary>
        /// 采购单接口
        /// </summary>
        public IOrderPoServices Services { get; }

        /// <summary>
        /// 帮助类
        /// </summary>
        public LogHelper LogHelper { get; }

        public OrderPoController(IOrderPoServices services, LogHelper logHelper)
        {
            Services = services;
            LogHelper = logHelper;
        }

        /// <summary>
        /// 获取所有采购单
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetAll")]
        public async Task<IActionResult> GetAll()
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var list = await Services.GetAllAsync();
                status.Data = list;
                status.Count = list.Count();
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("采购单-获取所有", ex, HttpContext);
            }
            return Ok(status);
        }

        /// <summary>
        /// 分页获取采购单
        /// </summary>
        /// <param name="PageIndex">当前页</param>
        /// <param name="PageSize">页大小</param>
        /// <param name="Number">采购单编号</param>
        /// <param name="VendorId">供应商名称</param>
        /// <param name="WarehouseId">入货仓</param>
        /// <param name="Status">单据状态：-1：全部，0待审核  1已审核</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Get([FromQuery] int PageIndex, [FromQuery] int PageSize, [FromQuery] string Number, [FromQuery] string VendorId, [FromQuery] string WarehouseId, [FromQuery] int Status=-1)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                Number = Number ?? "";
                VendorId = VendorId ?? "";
                WarehouseId = WarehouseId ?? "";
                var list = await Services.GetAsync(PageIndex, PageSize, Number, VendorId, WarehouseId, Status);
                status.Data = list;
                status.Count = await Services.GetCountAsync(Number, VendorId, WarehouseId, Status);
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("采购单-分页获取", ex, HttpContext);
            }
            return Ok(status);
        }

        /// <summary>
        /// 根据报价单Id获取采购数据
        /// </summary>
        /// <param name="OrderPoId">单据Id</param>
        /// <param name="WarehouseId">仓库Id</param>
        /// <returns></returns>
        [HttpGet("GetOrderPoId")]
        public async Task<IActionResult> GetOrderPoId([FromQuery] string OrderPoId, string WarehouseId)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var list = await Services.GetOrderPoIdAsync(OrderPoId, WarehouseId);
                status.Data = list;
                status.Count = list.Count();
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("采购单-获取设备资源", ex, HttpContext);
            }
            return Ok(status);
        }

        /// <summary>
        /// 新增采购单
        /// </summary>
        /// <param name="model">采购单模型</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Add([FromForm] OrderPo model, [FromForm] string OrderPoItemString)
        {
            var status = BaseStatus.CreateInstance();
            List<OrderPoItem> list = new List<OrderPoItem>();
            try
            {
                if (!string.IsNullOrEmpty(OrderPoItemString))
                {
                    list = JsonConvert.DeserializeObject<List<OrderPoItem>>(OrderPoItemString);
                    list.ForEach(x =>
                    {
                        x.CreateTime = StringHelper.GetTimeNow();
                        x.Creator = User.Identity.Name;
                    });
                }
                model.CreateTime = StringHelper.GetTimeNow();
                model.Creator = User.Identity.Name;
                var isSuccess = await Services.AddAsync(model,list);
                if (isSuccess)
                {
                    status.Msg = "新增成功";
                }
                else
                {
                    status.Code = -1;
                    status.Msg = "新增失败，请检查数据";
                }

            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("采购单-新增", ex, HttpContext);
            }
            return Ok(status);
        }

        /// <summary>
        /// 采购单修改
        /// </summary>
        /// <param name="model">采购单模型</param>
        /// <returns></returns>
        [HttpPut]
        public async Task<IActionResult> Update([FromForm] OrderPo model, [FromForm] string OrderPoItemString)
        {
            var status = BaseStatus.CreateInstance();
            List<OrderPoItem> list = new List<OrderPoItem>();
            try
            {
                if (!string.IsNullOrEmpty(OrderPoItemString))
                {
                    list = JsonConvert.DeserializeObject<List<OrderPoItem>>(OrderPoItemString);
                    list.ForEach(x =>
                    {
                        x.CreateTime = StringHelper.GetTimeNow();
                        x.UpdateTime = StringHelper.GetTimeNow();
                        x.Creator = User.Identity.Name;
                        x.OrderPoId = model.Id;
                    });
                }
                model.UpdateTime = StringHelper.GetTimeNow();
                model.Updater = User.Identity.Name;

                var isSuccess = await Services.UpdateAsync(model,list);
                if (isSuccess)
                {
                    status.Msg = "修改成功";

                }
                else
                {
                    status.Code = -1;
                    status.Msg = "修改失败，请检查数据";
                }

            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("采购单-修改", ex, HttpContext);
            }
            return Ok(status);
        }

        /// <summary>
        /// 批量删除采购单
        /// </summary>
        /// <param name="Ids">Id数组</param>
        /// <returns></returns>
        [HttpDelete("DelAll")]
        public async Task<IActionResult> DelAll([FromForm] string Ids)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var arr = Ids.SplitId();
                var isSuccess = await Services.DeleteAsync(arr);
                if (isSuccess)
                {
                    status.Msg = "删除成功";
                }
                else
                {
                    status.Code = -1;
                    status.Msg = "删除失败，请稍后重试";
                }
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("采购单-批量删除", ex, HttpContext);
            }
            return Ok(status);
        }

        /// <summary>
        /// 单个删除采购单
        /// </summary>
        /// <param name="Id">Id数组</param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<IActionResult> Del([FromForm] int Id)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var isSuccess = await Services.DeleteAsync(Id);
                if (isSuccess)
                {
                    status.Msg = "删除成功";
                }
                else
                {
                    status.Code = -1;
                    status.Msg = "删除失败，请稍后重试";
                }
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("采购单-删除", ex, HttpContext);
            }
            return Ok(status);
        }

        /// <summary>
        /// 修改采购订单状态
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="Status"></param>
        /// <returns></returns>
        [HttpPut("UpdateOrderPoStatus")]
        public async Task<IActionResult> UpdateOrderPoStatus([FromForm] long Id, [FromForm] int Status)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                // 根据报价单 Id 查询数据库，找到对应的报价单对象
                var isSuccess = await Services.UpdateOrderPoStatus(Id, Status);


                if (isSuccess)
                {
                    var msg = Status == 0 ? "反审成功" : "审核成功";
                    status.Code = 0;
                    status.Msg = msg;
                }
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("采购订单-修改状态", ex, HttpContext);
            }

            return Ok(status);
        }

        /// <summary>
        /// 导出
        /// </summary>
        /// <returns></returns>
        [HttpGet("Export")]
        public async Task<IActionResult> Export()
        {
            try
            {

                var list = await Services.GetAllAsync();
                var TitleArray = new ReportDomain[] {
                    new ReportDomain{ Title="序号",Fileld="No"},
                    new ReportDomain{ Title="采购单编号",Fileld="Number"},
                    new ReportDomain{ Title="供应商",Fileld="VendorName"},
                    new ReportDomain{ Title="入货仓",Fileld="WarehouseName"},
                    new ReportDomain{ Title="交货日期",Fileld="DeliveryDate"},
                    new ReportDomain{ Title="采购状态",Fileld="Status"},
                    new ReportDomain{ Title="创建时间",Fileld="CreateTime"},
                    new ReportDomain{ Title="货物状态",Fileld="State"},
                    new ReportDomain{ Title="备注",Fileld="Remark"},
                };
                var fileArray = BaseReport.Export(list, "采购订单信息", TitleArray);

                return File(new System.IO.MemoryStream(fileArray), "application/octet-stream", "采购订单信息.xls");
            }
            catch (Exception ex)
            {

                //此处应当日志记录
                await LogHelper.WriteErrorLog("采购订单-导出", ex, HttpContext);
                return new JsonResult(BaseStatus.CreateInstance(-1, "导出失败，服务器异常请稍后再试！"));
            }

        }
    }
}
